package com.sunny.ynhz.ui.index;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.BottomSheetBehavior;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import com.amap.api.location.AMapLocation;
import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.LatLng;
import com.sunny.ynhz.R;
import com.sunny.ynhz.bean.LocationBean;
import com.sunny.ynhz.bean.PatrolBean;
import com.sunny.ynhz.db.RealmUtils;
import com.sunny.ynhz.model.PatrolModel;
import com.sunny.ynhz.ui.report.ChooseRiverActivityNative;
import com.sunny.ynhz.ui.base.BaseFragment;
import com.sunny.ynhz.ui.daily.indexproblem.HistoryActivity;
import com.sunny.ynhz.ui.patrol.PatrolRiverMoreStyleActivity;
import com.sunny.ynhz.ui.patrol.problems.OtherProblemReportActivity;
import com.sunny.ynhz.ui.patrol.problems.draft.DraftActivity;
import com.sunny.ynhz.utils.AlertUtilsType;
import com.sunny.ynhz.utils.AnimatorUtils;
import com.sunny.ynhz.utils.CarUtils;
import com.sunny.ynhz.utils.LocationUtils;
import com.sunny.ynhz.utils.MeasureViewUtils;
import com.sunny.ynhz.utils.TimeFormatUtils;
import java.util.List;
import butterknife.BindView;
import butterknife.OnClick;
import io.realm.Realm;

/**
 * 巡河fragment
 * Created by luao on 2017/7/19.
 */

public class NewPatrolFragment extends BaseFragment implements LocationUtils.OnChangeLocation, AlertUtilsType.IClickButton, PatrolModel.IPatrolModel, MeasureViewUtils.IResultMeasure {
    @BindView(R.id.patrol_start)
    LinearLayout patrolStart;
    @BindView(R.id.patrol_problem_upload)
    LinearLayout patrolProblemUpload;
    @BindView(R.id.patrol_history)
    LinearLayout problemUploadWithoutPatrol;
    @BindView(R.id.draft)
    LinearLayout draft;
    @BindView(R.id.patrol_path_map)
    MapView patrolPathMap;
    @BindView(R.id.on_line)
    TextView reminder;
    @BindView(R.id.text_patrol)
    TextView textPatrol;
    @BindView(R.id.other_problem_upload)
    LinearLayout otherProblemUpload;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.tv_distance)
    TextView tv_distance;
    @BindView(R.id.tv_last_start_time)
    TextView tv_last_start_time;
    @BindView(R.id.tv_gps)
    TextView tv_gps;
    @BindView(R.id.lv_duty_river)
    ListView lv_duty_river;
    @BindView(R.id.txtDuty)
    TextView tv_duty;
    @BindView(R.id.bottom_sheet)
    View btns;
    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;
    @BindView(R.id.img_show_hide)
    ImageView img_show_hide;
    @BindView(R.id.ll_patrol_bottom)
    LinearLayout ll_patrol_bottom;

    @BindView(R.id.ll_record_patrol_msg)
    LinearLayout ll_record_patrol_msg;

    @BindView(R.id.ll_record_patrol_msg1)
    LinearLayout ll_record_patrol_msg1;
    private AMap map;
    public PatrolModel patrolModel;
    private PatrolBean patrolBean;
    private int type = -1;
    private int ll_record_patrolHeight;
    private LocationUtils locationUtils;
    private BottomSheetBehavior<View> bottomSheetBehavior;
    private String riverName;
    private String riverId;
    private String sectionId;

    public static NewPatrolFragment getInstancePatrolFragment() {
        return new NewPatrolFragment();
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.fragment_patrol_path_news;
    }

    @Override
    protected void setUpView() {
        super.setUpView();
        initView();
        patrolModel = new PatrolModel(getContext(), map, this, this);
        initData();
        locationUtils = new LocationUtils(map, getContext(), this);
        locationUtils.positionInit();
        locationUtils.startLocation();
        if (patrolBean != null) {
            type = patrolModel.adjustContinuePatrolType(patrolBean);
        }
        if (type == 0) {//代表超过设定的30分钟继续巡河
            patrolModel.dialogUploadPatrol();
        }
        if (type == 1) {//代表没超过分钟
            patrolModel.disPlayContinuePatrol("", 1);
        }
    }

    public void initView() {
        map = patrolPathMap.getMap();
        patrolPathMap.onCreate(savedInstanceState);// 此方法必须重写
        MeasureViewUtils.getMeasureViewHight(ll_record_patrol_msg1, this);
        bottomSheetBehavior = BottomSheetBehavior.from(btns);
        bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
        bottomSheetBehavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {
            @Override
            public void onStateChanged(@NonNull View bottomSheet, int newState) {
                if (newState == BottomSheetBehavior.STATE_EXPANDED) {
                    img_show_hide.setImageResource(R.mipmap.ic_map_bottom);
                } else {
                    img_show_hide.setImageResource(R.mipmap.ic_map_top);
                }
            }

            @Override
            public void onSlide(@NonNull View bottomSheet, float slideOffset) {

            }
        });
    }

    public void initData() {
        patrolBean = patrolModel.getLastPatrolBean();
        if (patrolBean == null) {
            patrolModel.setLastPatrolMsg();
        }
    }


    @OnClick({R.id.patrol_start, R.id.ll_patrol_bottom, R.id.ll_bottom_img, R.id.patrol_history, R.id.draft, R.id.other_problem_upload, R.id.pollution_report, R.id.patrol_river_more_style, R.id.img_show_hide})
    public void onclickEven(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.patrol_start:
                String patrolStrMsg = textPatrol.getText().toString();
                if (patrolStrMsg.equals("开始巡河")) {
//                    int userType = -1;
//                    try {
//                        userType = Integer.parseInt(SPUtil.get("userType", "").toString());
//                    } catch (Throwable throwable) {
//                        ToastUtils.SingleToastUtil(activity, "未能获取用户等级");
//                    }
//                    if (!(userType == 6 || userType == 11 || userType == 15)) {
                        Intent intent = new Intent(activity, ChooseRiverActivityNative.class);
                        startActivityForResult(intent, 600);
//                    } else {
//                        riverName = "";
//                        riverId = "";
//                        patrolModel.disPlayContinuePatrol("", 4);
//                    }


                } else if (patrolStrMsg.equals("结束巡河")) {
                    boolean valid = patrolModel.adjustValidPatrol(patrolBean);
                    if (valid)
                        stopCurrentPatrol();
                    else
                        patrolModel.displayStopPatrolRiver(5);

                }
                break;
            case R.id.ll_patrol_bottom:
                ImageView img_bottom = (ImageView) ll_patrol_bottom.getChildAt(0);
                if (ll_record_patrol_msg.getMeasuredHeight() == 0) {
                    img_bottom.setImageResource(R.mipmap.ic_btn_top);
                    AnimatorUtils.startAnimation(0, ll_record_patrolHeight, ll_record_patrol_msg);
                } else {
                    img_bottom.setImageResource(R.mipmap.ic_btn_down);
                    AnimatorUtils.startAnimation(ll_record_patrolHeight, 0, ll_record_patrol_msg);
                }
                break;
            case R.id.patrol_history:
                doActivity(HistoryActivity.class);
                break;
            case R.id.draft:
                doActivity(DraftActivity.class);
                break;
            case R.id.other_problem_upload:
                Intent intent = new Intent(activity, OtherProblemReportActivity.class);
                intent.putExtra("isPatroling", patrolModel.getPatrolRiver());
                if (patrolBean != null && patrolModel.getPatrolRiver()) {
                    intent.putExtra("patrolId", patrolBean.getId());
                    intent.putExtra("riverName", patrolBean.getRiverName());
                    intent.putExtra("riverId", patrolBean.getSectionId());
                    intent.putExtra("selectId", patrolBean.getRiverId());
                }
                startActivity(intent);
                break;
            case R.id.pollution_report:
//                doActivity(PollutantSoureActivity.class);
                break;
            case R.id.patrol_river_more_style:
                doActivity(PatrolRiverMoreStyleActivity.class);
                break;
            case R.id.img_show_hide:
                if (bottomSheetBehavior.getState() == BottomSheetBehavior.STATE_EXPANDED) {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_COLLAPSED);

                } else {
                    bottomSheetBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
                }
                break;
            default:
                break;
        }
    }
    /**
     * @param latLng 定位得坐标
     */
    @Override
    public void onLocation(LatLng latLng) {
        if (patrolModel.getPatrolRiver()) {
            LocationBean locationBean = new LocationBean();
            locationBean.setLgtd(latLng.longitude);
            locationBean.setLttd(latLng.latitude);
            locationBean.setTime(TimeFormatUtils.getTime());
            patrolModel.addLocaltionLatlng(locationBean, patrolBean);
            patrolModel.drawLinkLine(latLng);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 600) {
            riverName = data.getStringExtra("name");
            riverId = data.getStringExtra("reachId");//河涌id
            sectionId = data.getStringExtra("id");//河段id
            patrolModel.disPlayContinuePatrol(riverName, 4);
        }
    }

    @Override
    public void onAccuracyStatus(int status) {
        switch (status) {
            case AMapLocation.GPS_ACCURACY_GOOD://卫星信号强
                tv_gps.setText("GPS信号强");
                break;
            default://卫星信号弱
                tv_gps.setText("GPS信号较弱");
                break;
        }

    }

    @Override
    public void onFirstLocationSuccess() {
        String textPatrolStr = textPatrol.getText().toString();
        if (textPatrolStr.equals("正在定位")) {
            textPatrol.setText("开始巡河");
            reminder.setText("定位成功");
        }

    }

    @Override
    public void ensure(int type) {
        if (type == 2) {//停止巡河
            patrolModel.stopPatrol(true, patrolBean);
            initStopRiver();//初始化控件
        } else if (type == 1) {//继续巡河
            patrolModel.startTimeKeeper(patrolBean);
            patrolModel.setIsPatrolRiver(true);
            LatLng firstPositionLatlng = patrolModel.getFirstPosition();
            patrolModel.drawStartMark(firstPositionLatlng);
            patrolModel.drawPtrolLine(patrolModel.getLastPatrolRiverRoute(patrolBean), map);
            textPatrol.setText("结束巡河");
            reminder.setText("正在巡河");

        } else if (type == 0) {

        } else if (type == 4) {
            initStartPatrol();

        } else if (type == 5) {//结束巡河
            stopCurrentPatrol();
        }
    }

    public boolean isPatrolling() {
        return patrolModel.getPatrolRiver();
    }

    @Override
    public void cancel(int type) {
        if (type == 2 || type == 1) {
            patrolModel.deleteCurrentPatrolBean(patrolBean);
            initStopRiver();
        }
    }

    public void stopCurrentPatrol() {
        LatLng lastPositionLatlng = patrolModel.getLastPositionLatlng(patrolBean);
        patrolModel.setIsPatrolRiver(false);
        patrolModel.drawEndMark(lastPositionLatlng);
        patrolModel.stopPatrol(true, patrolBean);
        initStopRiver();
    }

    private void initStartPatrol() {
        CarUtils.getInstanceCarutils().resetCurrentDistance();
        textPatrol.setText("结束巡河");
        reminder.setText("正在巡河");
        patrolModel.setIsPatrolRiver(true);
        patrolModel.cleatMap();//清楚以前的标记
        patrolBean = patrolModel.createPatrolBean();
        if (!TextUtils.isEmpty(riverId)) {
            RealmUtils.getDeleteRealm().executeTransaction(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    patrolBean.setRiverId(riverId);
                    patrolBean.setSectionId(sectionId);
                    patrolBean.setRiverName(riverName);
                }
            });
        }
        LatLng currentPosition = patrolModel.getFirstPosition();
        patrolModel.drawStartMark(currentPosition);//绘制起点
        List<LatLng> lastPatrolRiverRoute = patrolModel.getLastPatrolRiverRoute(patrolBean);
        patrolModel.drawPtrolLine(lastPatrolRiverRoute, map);
        patrolModel.startTimeKeeper(patrolBean);
        patrolModel.startPatrol(patrolBean);

    }

    private void initStopRiver() {
        textPatrol.setText("开始巡河");
        reminder.setText("定位成功");
        patrolModel.stopTimeKeeper();
        patrolModel.setLastPatrolMsg();
    }

    @Override
    public void patrolRiverTime(String time) {
        tv_time.setText("巡河时长:" + time);
    }

    @Override
    public void distancePatrol(String distance) {
        tv_distance.setText("巡河距离:" + distance);

    }

    @Override
    public void startPatrolTime(String startTime) {
        tv_last_start_time.setText("巡河开始时间:" + startTime);
    }

    @Override
    public void lastpatrolRiverTime(String time) {
        tv_time.setText("上次巡河时长:" + time);
    }

    @Override
    public void lastdistancePatrol(String distance) {
        tv_distance.setText("上次巡河距离:" + distance);
    }

    @Override
    public void laststartPatrolTime(String startTime) {
        tv_last_start_time.setText("上次开始时间:" + startTime);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        patrolModel.stopTimeKeeper();
        locationUtils.destroyLocation();
    }

    @Override
    public void resultHigh(int high) {
        ll_record_patrolHeight = high;
    }

}